import OrderCard from "@/components/OrderCard";
import Page from "@/components/page"
import { GoodsFields } from "@/interfaces/GoodsEntity";
import { OrderEntity, OrderFields } from "@/interfaces/OrderEntity";
import { ShopFields } from "@/interfaces/ShopEntity";
import { UserFields } from "@/interfaces/UserEntity";
import { OrderOnGoodsFields } from "@/interfaces/order-goods.entity";
import { useQuery, useMutation, gql } from "@apollo/client";
import { useMemo, useCallback } from "react";

const SelSelfOrderQuery = gql`
  query SelSelfOrder{
    getSelfAllOrder{
      ${OrderFields}
      OrderOnGoods{
        ${OrderOnGoodsFields}
        goods{
          ${GoodsFields}
        }
      }
      shop{
        ${ShopFields}
      }
      user{
        ${UserFields}
      }
    }
  }
`
const DeliveryOrderMutation = gql`
    mutation DeliveryOrder($id:Int!){
        deliveryOrder(id:$id){
            id
        }
    }
`
const OrderGoodsPage = () => {
    const { data, refetch } = useQuery(SelSelfOrderQuery)
    const orders: OrderEntity[] = useMemo(() => data?.getSelfAllOrder || [], [data]);
    const [deliveryOrder] = useMutation(DeliveryOrderMutation, {
        onCompleted() {
            refetch()
        }
    })
    const onFinish = useCallback((order: OrderEntity) => {
        deliveryOrder({ variables: { id: order.id } })
    }, [])
    return (
        <Page>
            <div className="flex flex-wrap gap-4">
                {orders.map((order) => (
                    <OrderCard
                        key={order.id}
                        order={order}
                        onFinish={onFinish}
                    />
                ))}
            </div>
        </Page>
    )
}
export default OrderGoodsPage